import { useEffect, useState } from 'react';
import { message, Table, Popconfirm } from 'antd';
import { getGoodsList, getGoodsDelete } from '../../api/goods'
import type { GoodsData, pageGationGoodsData } from '../../types/goods';
import { GoodsColumnsList } from './columns'
import SearchForm from './SearchForm'
import GoodsAddOrEdit from './GoodsAddOrEdit';

const GoodsList:React.FC = () => {
  const [goodsList, setGoodsList] = useState<GoodsData[]>([]);
  const [columns, setColumns] = useState<any[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [selectedId, setSelectedId] = useState<number | null>(null);
  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    hideOnSinglePage: false,
    pageSizeOptions: ['10', '50', '100', '200'],
    showTotal: (total: number) => `共 ${total} 条数据`,
  })
  const [queryParams, setQueryParams] = useState<pageGationGoodsData>({
    page: 1,
    pageSize: 10,
    goodsname: '',
  })

  const getTableColmuns = async () => {
    var columns = [];
    const goodsColumns: any = await GoodsColumnsList();
    columns = [
      ...goodsColumns,
      {
        title: '操作',
        key: 'operation',
        align: 'center',
        width: 120,
        render: (_text: any, record: any) =>
          [
            <div className='goods_opertion'>
              <div key={`${record.id}-update`} onClick={() => handleUpdateClick(record.id)}>修改</div>
              <Popconfirm
                title="确定要删除这条记录吗？"
                onConfirm={() => {
                  try {
                    getGoodsDelete({
                      id: record.id
                    }).then((res: any) => {
                      if (res.data.code === 200) {
                        message.success('删除成功');
                        fetchData();
                      } else {
                        message.error(res.data.message);
                      }
                    })
                  } catch (error) {
                    message.error('删除失败!');
                  }
                }
                }
                okText="确定"
                cancelText="取消"
              >
                <div key={`${record.id}-delete`}>删除</div>
              </Popconfirm>
            </div>
          ]
      }
    ];
    return columns; // 确保返回值 
  }

  const handleUpdateClick = (id: number) => {
    setSelectedId(id);
    setVisible(true);
  };
  
  const getGoodsListData = async () => {
    try {
      const res = await getGoodsList(queryParams);
      if (res.data.code === 200) {
        setGoodsList(res.data.data);
        setPagination({
          ...pagination,
        })
      } else {
        message.error(res.data.message);
      }
    } catch (error) {
      message.error('获取数据失败!');
    }
  }

  const fetchData = async () => {
    try {
      await getGoodsListData();
      const column = await getTableColmuns();
      setColumns(column);
    } catch (error) {
      message.error('获取数据失败!');
    }
  };

  useEffect(() => {
    fetchData();
  }, [])

  const handleMessageSearch = (msg: any) => {
    setQueryParams({ ...queryParams, goodsname: msg })
  };

  const getGoodsAdd = (msg: any) => {
    setVisible(msg)
  }

  const handleModalClose = () => {
    setVisible(false);
    setSelectedId(null);
  };

  useEffect(() => {
    getGoodsListData();
  }, [queryParams]);

  return (
    <>
      <SearchForm SumbitSearch={handleMessageSearch} SumbitAdd={getGoodsAdd} />
      <GoodsAddOrEdit visible={visible} onClose={handleModalClose} id={selectedId} onRefresh={fetchData} />
      <Table
        columns={columns}
        dataSource={goodsList}
        pagination={pagination}
        rowKey={(record: any) => `table_${record.id}`}
        scroll={{ x: 1200 }}
      />
    </>
  )
}
export default GoodsList;
